package com.yhos.platform.oopston.core.validator;

import com.yhos.platform.oopston.core.annotation.RegexValid;
import com.yhos.platform.oopston.core.exception.BusinessException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexValidator extends ConstraintValidator<RegexValid, Object> {

    private String regex;
    private String code;

    @Override
    public void initialize(RegexValid constraintAnnotation) {
        regex = constraintAnnotation.regex();
        code = constraintAnnotation.message();
    }

    @Override
    public boolean isValid(Object value) {
        if(value == null){
            return true;
        }

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(value.toString());
        if (!matcher.find()) {
            throw new BusinessException(code, code);
        }

        return true;
    }
}
